/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.database.datasource;

import com.robam.cloud.database.util.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020/7/4 17:44
 * @Version 1.0
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {


    private DataSource defaultTargetDataSource;
    protected Map<Object, Object> targetDataSources = new HashMap();


    @Override
    protected Object determineCurrentLookupKey() {
        String currentDB = DynamicDataSourceContextHolder.getMyDBType();
        return currentDB;
    }


    public void addTargetDataSource(String key, DataSource dataSource) {
        this.targetDataSources.put(key, dataSource);
        this.setTargetDataSources(this.targetDataSources);
    }


    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        log.debug("component-databaselog-----------设置AbstractRoutingDataSource-targetDataSources 数量{}", targetDataSources.size());
        super.setTargetDataSources(targetDataSources);
        this.targetDataSources = targetDataSources;
    }

    public void setDefaultTargetDataSource(DataSource defaultTargetDataSource) {
        log.debug("component-databaselog-----------设置AbstractRoutingDataSource-defaultTargetDataSource{}", defaultTargetDataSource);
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        this.defaultTargetDataSource = defaultTargetDataSource;
    }

    public Map<Object, Object> getTargetDataSources() {
        return this.targetDataSources;
    }

    public DataSource getDefaultTargetDataSource() {
        return defaultTargetDataSource;
    }
}
